import {defineConfig, loadEnv} from "vite"
import {fileURLToPath, URL} from "node:url"
import UnoCSS from "unocss/vite"
import AutoImport from "unplugin-auto-import/vite"
import Components from "unplugin-vue-components/vite"
import {ElementPlusResolver} from "unplugin-vue-components/resolvers"
import {createSvgIconsPlugin} from "vite-plugin-svg-icons"
import path from "path"
// import {viteMockServe} from "vite-plugin-mock"
import vue from "@vitejs/plugin-vue"
// @ts-ignore
import vueDevTools from 'vite-plugin-vue-devtools'
// import stylelint from 'vite-plugin-stylelint';

// https://vitejs.dev/config/
export default defineConfig(({mode}) => {
    //拿到配置的环境变量
    const env = loadEnv(mode, process.cwd())
    const isDev = env.VITE_USER_NODE_ENV === "development"
    const outDir = mode == 'production' ? 'dist_prod' : 'dist'
    console.log(env, mode)

    return {
        base: "./",
        logLevel: 'info',
        plugins: [
            vue(),
            UnoCSS(),
            isDev && vueDevTools({launchEditor: process.env.VITE_EDITOR}),
            // ...
            AutoImport({
                imports: ['vue', 'vue-router', 'pinia'], // 自动导入的依赖库数组
                dts: './auto-imports.d.ts', // 自动导入类型定义文件路径
                resolvers: [
                    ElementPlusResolver(), // 自动导入图标组件
                ],
            }),
            // //mock
            // viteMockServe({
            //     mockPath: "./src/mock",
            //     // localEnabled: true,
            // }),
            // 主题定制
            Components({
                resolvers: [ElementPlusResolver({importStyle: "sass"})],
                // 指定自定义组件位置(默认:src/components)自动注册全局组件
                dirs: [
                    "src/components/ElementPlus_components/",
                    "src/components/",
                    "src/**/components",
                ],
                // 生成components.d.ts
                dts: false,
                deep: true,
            }),
            createSvgIconsPlugin({
                iconDirs: [path.resolve(process.cwd(), "src/assets/svgs")],
                symbolId: "icon-[dir]-[name]",
            }),
        ],
        resolve: {
            alias: {
                "@": fileURLToPath(new URL("./src", import.meta.url)),
            },
        },
        //主题定制(主题覆盖)
        css: {
            preprocessorOptions: {
                scss: {
                    silenceDeprecations: ['legacy-js-api'],
                    api: "modern-compiler",
                    warnRuleAsWarning: false, // 关闭规则警告
                    sassOptions: {
                        quietDeps: true, // 关闭依赖警告
                    },
                    additionalData: `  
                    @use "@/styles/element/index.scss" as *;
                    @use "@/config/public.scss" as *;
                    `,
                },
            },
        },
        //配置代理跨域
        server: {
            port: 9900, //自定义端口
            proxy: {
                [env.VITE_BASE_URL]: {
                    target: env.VITE_URL,
                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/api/, ""),
                },
            },
        },
        build: {
            minify: 'esbuild',//isDev ? 'esbuild' : 'terser', // 是否进行压缩,boolean | 'terser' | 'esbuild',默认使用terser
            manifest: false, // 是否产出manifest.json
            sourcemap: false, // 是否产出sourcemap.json
            outDir: outDir, // 产出目录
            assetsInlineLimit: 4096,
            cssCodeSplit: true,
            reportCompressedSize: false,
            chunkSizeWarningLimit: 2000,
            terserOptions: {
                compress: {
                    drop_console: true, // 删除 console
                    drop_debugger: true, // 删除 debugger
                },
                format: {
                    comments: false // 删除所有注释
                }
            },
            rollupOptions: {
                output: {
                    entryFileNames: `assets/jihuoniao_app.[hash:8].js`,
                    chunkFileNames: `assets/js/jihuoniao_[name].[hash:8].js`,
                    // assetFileNames: 'assets/[ext]/jihuoniao_[name].[hash].[ext]',
                    assetFileNames: (assetInfo: any) => {
                        const imgExt = ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.svg', '.ico']
                        if (imgExt.some(ext => assetInfo.name.endsWith(ext))) {
                            return 'assets/img/jihuoniao_[name].[hash:8].[ext]'
                        }
                        if (assetInfo.name.endsWith('.css')) {
                            return 'assets/css/jihuoniao_[name].[hash:8].[ext]'
                        }
                        return 'assets/[ext]/jihuoniao_[name].[hash:8].[ext]';
                    },
                    compact: true,
                    manualChunks: {
                        vue: ['vue', 'pinia', 'vue-router'],
                        'element-plus': ['element-plus', '@element-plus/icons-vue'],
                        axios: ['axios'],
                        lodash: ['lodash'],
                        echarts: ['echarts', 'zrender']
                    },
                },
            }
        },
    }
})
